/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.liycloud.common.security.component;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.client.RestTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;

import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.authentication.TokenExtractor;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * @author lengleng
 * @date 2018/6/22
 *
 * 资源服务器 ResourceServer 配置类,  资源服务器配置主要在这里完成配置
 *
 * <p>
 * 1. 支持remoteTokenServices 负载均衡
 * 2. 支持 获取用户全部信息
 */
@Slf4j
public class PigxResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {

	@Autowired
	protected AuthenticationEntryPoint resourceAuthExceptionEntryPoint;

	/*
	 * 远程Token服务, 在认证服务器
	 */
	@Autowired
	protected RemoteTokenServices remoteTokenServices;


	/*
	 * 框架: 配置 ${security.oauth2.client.ignore-urls}  不需要进行权鉴, 直接可以访问的url 配置类
	 */
	@Autowired
	private PermitAllUrlProperties permitAllUrlProperties;

	/*
	 * Token 提取器
	 */
	@Autowired
	private TokenExtractor tokenExtractor;

	/**
	 * 负载均衡加强版 RestTemplate,
	 * @see PigxResourceServerAutoConfiguration   在这里配置注入容器的
	 *
	 */
	@Autowired
	private RestTemplate lbRestTemplate;


	/**
	 * 配置对外暴露 不需要认证的 url
	 * @param httpSecurity
	 */
	@Override
	@SneakyThrows
	public void configure(HttpSecurity httpSecurity) {

		// 允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
		httpSecurity.headers().frameOptions().disable();

		//  表达式 Url 权鉴配置                              表达式 拦截 Url 注册表
		ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();

		// 从忽略配置对象中遍历获取 配置的url
		permitAllUrlProperties.getIgnoreUrls().forEach(url -> {
					registry.antMatchers(url).permitAll();  //注册表添加 满足该 url 的全部放开, 不做认证权限拦截
				}
		);

		registry.anyRequest().authenticated()   // 其他请求 全部需要认证
				.and()
				.csrf().disable();
	}


	/**
	 * 资源服务器安全配置
	 * @param resources
	 */
	@Override
	public void configure(ResourceServerSecurityConfigurer resources) {

		// 用户权限类转换器     Authentication  <->  Map<String, ?>  这两者相互转换
		UserAuthenticationConverter userTokenConverter = new PigxUserAuthenticationConverter();


		// 默认 Token 转换器
		DefaultAccessTokenConverter defaultAccessTokenConverter = new DefaultAccessTokenConverter();
		defaultAccessTokenConverter.setUserTokenConverter(userTokenConverter);


		// 远程token服务
		remoteTokenServices.setRestTemplate(lbRestTemplate); //
		remoteTokenServices.setAccessTokenConverter(defaultAccessTokenConverter);  // token 转换器

		resources.authenticationEntryPoint(resourceAuthExceptionEntryPoint)  // 异常处理入口点
				.tokenExtractor(tokenExtractor)
				.tokenServices(remoteTokenServices);
	}

}
